<?php

namespace app\factory\logic;

use app\common\exception\LogicException;
use app\model\Medicine;
use think\Exception;
use think\facade\Db;

class MedicineLogic
{
    protected Medicine $model;
    protected int $factory_id;

    public function __construct()
    {
        $this->model = new Medicine();
        $this->factory_id = request()->factory_info['factory_id'];
    }

    /**
     * @Description 新增/编辑
     * @author: zj
     * @param int $Id
     * @param array $param
     * @time 2024/03/22 11:15:43
     * @return true
     */
    public function addEdit(int $Id,array $param)
    {
        Db::startTrans();
        try {
            $exist = $this->model->checkOutIdIsExist($this->factory_id,$Id);
            if ($exist) {
                $rule = [
                    'Name' => 'max:255',
                    'Type' => 'integer|in:10,20'
                ];
                validate($rule)->check($param);

                $updateData = [];
                if ($param['Name']) {
                    $medicine = $this->model->checkNameIsExist($this->factory_id,$param['Name']);
                    if ($medicine && $medicine != $exist) {
                        throw new Exception('药品已存在');
                    }
                    $updateData['name'] = $param['Name'];
                }
                if ($param['Type']) {
                    $updateData['type'] = $param['Type'];
                }
                $updateData['update_record_time'] = $param['RecordTime'];
                $updateData['update_time'] = request()->time();

                $this->model->where('out_id',$Id)
                    ->where('delete_time',$this->model::IS_DELETE_NO)
                    ->update($updateData);
            } else {
                $rule = [
                    'Name' => 'require|max:255',
                    'Type' => 'require|integer|in:10,20'
                ];
                validate($rule)->check($param);

                $this->model->insert([
                    'out_id' => $Id,
                    'factory_id' => $this->factory_id,
                    'name' => $param['Name'],
                    'type' => $param['Type'],
                    'record_time' => $param['RecordTime'],
                    'update_record_time' => $param['RecordTime'],
                    'create_time' => request()->time(),
                    'update_time' => request()->time()
                ]);
            }

            Db::commit();
        }catch (\Exception $exception) {
            Db::rollback();
            throw new LogicException($exception->getMessage());
        }

        return true;
    }

}